﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel;

namespace TaskRecord.Web.Common
{
    public class ControllerFactory<TControllerToProvideNamespace> : DefaultControllerFactory
       where TControllerToProvideNamespace : Controller
    {
        private readonly IKernel _kernel;

        public ControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        override protected Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            Type controllerType = null;

            var baseNamespace = typeof(TControllerToProvideNamespace).Namespace;

            var fullName = string.Format("{0}.{1}Controller", baseNamespace, controllerName);
            controllerType = Type.GetType(fullName);

            return controllerType ?? base.GetControllerType(requestContext, controllerName);
        }

        override public void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
        }

        override protected IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }
            return (IController)_kernel.Resolve(controllerType);
        }
    }
}